<?php


namespace App\Http\Controllers\Agent;


use App\Contract\Platform;
use App\Http\Service\DeviceService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Controller;
use App\Model\Agent;
use App\Model\Device;
use App\Model\TestRecord;
use App\Tools\Helper;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class LoginController extends Controller
{
    /**登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $username = $request->input('mobile');
        $password = $request->input('password');
        if (!$username OR !$password) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        $staff = Agent::where('mobile', $username)->first();
        if (!$staff) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        if (!password_verify($password, $staff->password)) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        if (!$staff->token) {
            $staff->token = Str::random(32);
            $staff->save();
        }
        return Result::success([
            'token' => $staff->token,
            'name' => $staff->name,
            'mobile' => $staff->mobile,
        ]);
    }


    /**注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request): \Illuminate\Http\JsonResponse{
        $username = $request->input('mobile');
        $password = $request->input('password');
        $name = $request->input('name','');
        if (!$username OR !$password) {
            return Result::error(400, '注册失败，请完善账号或密码');
        }
        $check = Agent::where('mobile',$username)->count();
        if($check){
            return Result::error(1001,'手机号已注册');
        }
        $save['mobile'] = $username;
        if(!$name){
            $save['name']= '匿名商户'.substr($username, -4);
        }else{
            $save['name'] = $name;
        }
        $save['password'] =  Hash::make($password);
        if(Agent::create($save)){
            return Result::success();
        }
        return Result::error();
    }

    /**获取登录态
     * @return \Illuminate\Http\JsonResponse
     */
    public function authInfo(): \Illuminate\Http\JsonResponse
    {
        $staff = Token::getUser();
        if($staff->pid){
            $service_fee = Agent::query()->where('id',$staff->pid)
                ->value('service');
        }else{
            $service_fee = $staff->service;
        }
        return Result::success([
            'name' => $staff->name,
            'mobile' => $staff->mobile,
            'avatar'=>$staff->avatar,
            'amount'=>$staff->amount,
            'total_amount' =>$staff->total_amount,
            'total_fee'=>$staff->total_fee,
            'rate'=>$staff->rate,
            'pid'=>$staff->pid,
            'tel_no'=>$staff->tel_no,
            'type'=>$staff->type,
            'service'=>$staff->service,
            'service_fee'=>$staff->service_fee
        ]);
    }

    /**创建子经销商
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request):\Illuminate\Http\JsonResponse{
        $agent = Token::getUser();
        if($agent->pid){
            return Result::error(1001,'当前仅支持二级分销商');
        }
        $password = $request->input('password');
        $name = $request->input('name');
        $rate = $request->input('rate');
        $mobile = $request->input('mobile');
        $tel_no = $request->input('tel_no');
        $type = $request->input('type',1);
        $service = $request->input('service',0);

        $check = Agent::query()->where('mobile',$mobile)->first();
        if($check){
            return Result::error(1001,'手机号已存在');
        }

        if($rate > 0.3){
            return Result::error(1001,'分润比例不得超过百分之0.3');
        }
        $agentModel = new Agent();
        $agentModel->password = Hash::make($password);
        $agentModel->mobile = $mobile;
        $agentModel->rate = $rate;
        $agentModel->name = $name;
        $agentModel->pid = $agent->id;
        $agentModel->tel_no = $tel_no;
        $agentModel->type = $type;
        $agentModel->service = $service;
        $agentModel->save();
        return Result::success();
    }

    public function changePassword(Request $request): \Illuminate\Http\JsonResponse
    {
        $newPassword = $request->input('newPassword');
        $oldPassword = $request->input('oldPassword');
        $staff = Token::getUser();
        if (!$newPassword OR !$oldPassword) {
            return Result::error(400, '缺少字段');
        }
        if (!password_verify($oldPassword, $staff->password) && env('APP_ENV') == 'production') {
            return Result::error(400, '原密码错误');
        }
        $staff->password = Hash::make($newPassword);
        $staff->save();

        return Result::success();
    }

    public function getAmount(Request $request){
        $agent = Token::getUser();
        $data = Agent::query()->where('id',$agent->id)->first(['amount','total_amount']);
        return Result::success($data);
    }

    /**通用编辑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request): \Illuminate\Http\JsonResponse{
        $name = $request->input('name');
        $avatar = $request->input('avatar');
        $rate = $request->input('rate');
        $agent_id = $request->input(['agent_id']);
        $tel_no = $request->input('tel_no');
        $service = $request->input('service');
        $agent = Token::getUser();
        if(!$agent_id){
            $agent_id = $agent->id;
            $rate = 0;
        }
        $agentModel = Agent::query()->where('id',$agent_id)->first();
        if(!$agentModel){
            return Result::error(400, '原密码错误');
        }
        if($name){
            $agentModel->name = $name;
        }
        if($service != ''){
            $agentModel->service = $service;
        }
        if($avatar){
            $agentModel->avatar = $avatar;
        }
        if($rate != ''){
            if(!is_numeric($rate)){
                $rate = 0;
            }
            $agentModel->rate = $rate;
        }
        if($tel_no){
            $agentModel->tel_no = $tel_no;
        }
        $agentModel->save();
        return Result::success();
    }

    /**子经销商数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function childList(Request $request):\Illuminate\Http\JsonResponse{
        $agent = Token::getUser();
        if($agent->search_type == 2){
            $data = Agent::query()->where('pid',$agent->id)->whereNull('deleted_at')
                ->orderBy('sort','desc')
                ->orderBy('id','desc')->get(['id','name','rate','mobile','avatar','service','type','pid']);
        }else{
            $data = Agent::getAllCategories();
            foreach($data as $k => &$v){
                $prefix = '';
                for($i = 0; $i<$v['level']; $i++){
                    $prefix.='------';
                }
                $v['name'] = $prefix.$v['name'];
            }
        }
        return Result::success($data);
    }

    /**保存最新默认
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveTemp(Request $request):\Illuminate\Http\JsonResponse{
        $data = $request->input('data');
        $key = 'RECORD_TEMP_CACHE';
        $cache = Cache::put($key, json_encode($data));
        return Result::success();
    }

    /**获取最新默认
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemp(Request $request):\Illuminate\Http\JsonResponse{
        $key = 'RECORD_TEMP_CACHE';
        $value = Cache::get($key);
        if($value){
            $value  = json_decode($value);
        }else{
            $value = [];
        }
        return Result::success($value);
    }


    /**检查是否已测
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkTest(Request $request):\Illuminate\Http\JsonResponse{
        $mac= $request->input('mac');
        $check = Device::where('mac',$mac)->first();
        if($check){
            $data['is_check'] = 1;
            $data['sn'] = $check->sn;
        }else{
            $data['is_check'] = 0;
            $data['sn'] = '';
        }
        return Result::success($data);
    }

    /**根据设备号获取信号值
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSignal(Request $request):\Illuminate\Http\JsonResponse{
        $sn = $request->input('sn');
        $device = Device::query()->where('sn','=',$sn)->first(['id','name','sn','net_type',
            'mac','signal','online_status','online_at']);
        $device['sn'] = $sn;
        return Result::success($device);
    }

    /**产测接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function testRecord(Request $request): \Illuminate\Http\JsonResponse
    {
        $validData = $request->validate([
            'mac' => 'required',
            'sn' => 'required',
            'name' => 'required',
            'overload_i' => 'required',
            'step_2' => 'required',
            'step_3' => 'required',
            'step_4' => 'required',
            'error_ratio' => 'required',
            'device_type' => 'required|in:' . Helper::keysToString(TestRecord::DEVICE_TYPE_MAP),
        ], [], [
            'mac' => 'mac地址',
            'sn' => '二维码编号',
            'name' => '蓝牙名称',
            'overload_i' => '过载电流',
            'step_2' => '校表',
            'step_3' => '开闸/合闸',
            'step_4' => '清表',
            'error_ratio' => '精度误差',
            'device_type' => '设备类型',
        ]);

        if(Str::contains($request->sn, 'sn=')) {
            $validData['sn'] = explode('sn=', $request->sn)[1];
        }

        if(TestRecord::whereSn($request->sn)->exists()) {
            return Result::error(400,'该二维码设备已经测试过了');
        }

        if(TestRecord::where('name', $request->name)->exists()) {
            return Result::error(400,'该蓝牙设备已经测试过了');
        }
        $mac = str_replace(":", "", $request->input('mac'));
        $sn = $request->input('sn');
        $deviceModel = Device::query()->where('mac', $mac)
            ->orWhere('sn', $sn)->first();
        if ($deviceModel && $deviceModel->mac == $mac) {
            return Result::error(401, 'MAC地址已存在');
        }
        if ($deviceModel) {
            return Result::error(401, '二维码编号已存在');
        }

        $agent = Token::getUser();
        $testRecord = new TestRecord($validData);
        $testRecord->user_id = $agent->id;
        $testRecord->mobile = $agent->mobile;
        $testRecord->save();
        $type = $request->input('type',1);
        $deviceModel = new Device();
        $deviceModel->mac = $testRecord->mac;
        $deviceModel->name = $testRecord->name;
        $deviceModel->sn = $testRecord->sn;
        $deviceModel->type = $type;
        if($type == 3 || $type == 4){
            $deviceModel->month_limit = 1000;
            $deviceModel->business_amount = 1000;
        }else{
            $deviceModel->business_amount = 200;
        }
        $deviceModel->pay_mode = $request->input('pay_mode') == 2 ? 2 : 1;
        $deviceModel->net_type = $request->input('device_type') == 1 ? 1 : 2;
        if ($deviceModel->net_type == 1) {
            $deviceModel->is_master = 1;
        }
        if ($agent) {
            $deviceModel->agent_id = $agent->id;
        }
        $deviceModel->overload = $testRecord->overload_i;
        $deviceModel->expired_at = Carbon::now()->addYears(8)->toDateTimeString();
        $deviceModel->save();
        return Result::success();
    }



    # 拉闸
    public function stop(Request $request)
    {
        Log::info($request->input('mac'));
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->stop($request->input('mac'));

        return Result::success();
    }

    # 合闸
    public function start(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        Log::info($request->input('mac'));
        $result = $service->start($request->input('mac'));
        return Result::success();
    }

}
